import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//定义类型
const types = {
  SET_AUTHENTICATED: 'SET_AUTHENTICATED',
  SET_USER: 'SET_USER'
}


export default new Vuex.Store({
  state: {
    //定义状态,isAuthenticated默认是false
    isAuthenticated: false,
    user: {}
  },
  getters: {
    //相当于计算属性
    // 取到保存到vuex里的值
    isAuthenticated: state => state.isAuthenticated,
    user: state => state.user
  },
  mutations: {
    // 修改状态(同步)
    [types.SET_AUTHENTICATED](state, isAuthenticated) {
      if (isAuthenticated) {
        state.isAuthenticated = isAuthenticated;
      } else {
        state.isAuthenticated = false
      }
    },
    [types.SET_USER](state, user) {
      if (user) {
        state.user = user
      } else {
        state.user = {}
      }
    }
  },
  actions: {
    // 修改转台(异步)
    setAuthenticated: ({ commit }, isAuthenticated) => {
      commit(types.SET_AUTHENTICATED, isAuthenticated);
    },
    setUser: ({ commit }, user) => {
      commit(types.SET_USER, user)
    },
    clearCurrentState: ({ commit }) => {
      commit(types.SET_AUTHENTICATED, false);
      commit(types.SET_USER, null)
    }
  },
  modules: {
  }
})
